/* eslint-disable @iceworks/best-practices/recommend-polyfill */
import DrawerFooter from '@/components/DrawerFooter';
import { useStore } from '@/hooks';
import { Button, Dialog, Form, Table, Message, Input } from '@alifd/next';
import { t } from '@lingui/macro';
import { observable, runInAction } from 'mobx';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { apiLbs } from '@/services';
import { FieldsGrid, TitleGrid, column, model } from '../stores/definitions_plat';
import { deconstructionMapObj, arrTransferObj } from '@/utils/util';
import TauTable from '@/components/TauTable';
import MapModal from '@/components/MapModal';

const FromItem = Form.Item;

const { third } = model;

const DataForm = ({ data, modal, onSubmit, onCancel }) => {
  const { otherStationStore: store } = useStore();
  const [operationCompany, setOperationCompany] = useState([]);
  const isViewMode = modal === 'view';
  const formProps = isViewMode ? { field: false } : {};
  const [station] = useState(() => observable({}));
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const objRef = useRef();
  const [map, setMap] = useState({ show: false, coord: '', cityName: '' });

  useEffect(() => {
    (async () => {
      if (data) {
        editCtx.origin = _.cloneDeep(data);
        _.assign(station, data);
        setOperationCompany(data.third);
      }
    })();
  }, []);

  if (!station) return <></>;

  const overrideModel = {
    longLat: {
      ui: {
        renderer: (v, r) => <Input value={v} addonAfter={!isViewMode && <Button type="primary" onClick={() => handleMapOpen(r)}>{t`获取经纬度`}</Button>} />,
      },
    },
  };

  const handleChange = (values, item) => {
    const { name, value } = item;
    runInAction(() => {
      let handled = false;
      if (name === 'startMinorAreas') {
        _.set(station, 'startMinorAreas', [value]);
        handled = true;
      }
      if (name === 'endMinorAreas') {
        _.set(station, 'endMinorAreas', [value]);
        handled = true;
      }

      if (!handled) _.set(station, name, value);
      // 联动效果可以在这里通过设置price属性实现

      if (name === 'startMainArea') {
        _.unset(station, 'startMinorAreas');
      }

      if (name === 'endMainArea') {
        _.unset(station, 'endMinorAreas');
      }

      if (name === 'cprice.oneTripPrice.RMB' || name === 'cprice.roundTripPrice.RMB') {
        const prefix = _.trimEnd(name, '.RMB');
        _.set(station, `${prefix}.HKD`, parseFloat(value));
        _.set(station, `${prefix}.MOP`, parseFloat(value));
      }
    });

    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleMapOpen = async (other) => {
    const tempOther = toJS(other);
    objRef.current = tempOther;
    const { longLat = '', cityName, name } = tempOther;
    let coord = longLat;
    const currentCity = cityName
      .replace(/[（(][^）)]*[）)]/g, '')
      .replace(/[a-zA-Z]+/g, '');
    const currentName = name?.replace(/[（(][^）)]*[）)]/g, '');
    if (!longLat) {
      const r = await apiLbs.placeSearch({ region: currentCity, keyword: currentName });
      const { location } = r?.[0] || {};
      const { lat, lng } = arrTransferObj(location);
      if (location) coord = deconstructionMapObj({ lat, lng });
    }
    setMap({ show: true, coord, cityName: currentCity });
  };

  const handleCoordPicked = async (coord) => {
    const location = deconstructionMapObj(toJS(coord));
    _.set(station, 'longLat', location);
    setMap({ show: false });
  };

  const handleSubmit = (__, errors, ___) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: DataForm.jsx:101 _ errors:', errors);
      return;
    }
    onSubmit?.(station);
  };


  const handleCancel = () => {
    // eslint-disable-next-line no-param-reassign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => { v !== undefined && (r[k] = v); }))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form
      isPreview={isViewMode}
      {...formProps}
      inline
      value={station}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <TitleGrid title={t`基础信息`} />
      <FieldsGrid
        formData={station}
        overrideModel={overrideModel}
        mode={'view'}
        fields={['name', 'cityName', 'areaName', 'state',
          'onAddress', 'offAddress', 'type',
          'description', 'crDate', 'kind']}
      />
      <FieldsGrid
        formData={station}
        overrideModel={overrideModel}
        mode={modal}
        fields={['longLat']}
      />
      <TitleGrid title={t`关联平台站点`} />
      <>
        <TauTable
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          sort={store.tableSort}
          hidePagination
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={operationCompany}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('name', {}),
            column('id', {}),
            column('cityName', {}),
            column('areaName', {}),
            {
              title: t`上/下车站点详细地址`,
              cell: (v, __, r) => {
                const { onAddress, offAddress } = r;
                return (
                  <>
                    <span>{onAddress}</span>
                    <br />
                    <span>{offAddress}</span>
                  </>
                );
              },
            },
            column('longLat', {}, third),
          ]}
        />
      </>
      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
      <MapModal
        visible={map.show}
        coord={map.coord}
        cityName={map.cityName}
        containerId={'otherStation'}
        onClose={() => setMap({ show: false })}
        onCancel={() => setMap({ show: false })}
        onPick={handleCoordPicked}
      />
    </Form>
  );
};

export default observer(DataForm);
